import { isUndefiend, isEmpty } from '@/utils/lodash';

// 设置对象属性
const setObjectProps = (obj: any, key: string, value: any, type?: string) => {
  if(obj && !isUndefiend(key) && (type === 'boolean' || !isUndefiend(value))) {
    obj[key] = value || false;
  }
}

// 获取实际的菜单数组
const getConfigMenuArr = (configRoutes: Array<any>, level: number = 0, isDepth: boolean = false, pathname: string = ''): Array<any> => {

  const _configMenus: Array<any> = [];
  const configMenus: Array<any> = [];
  
  // 过滤属性添加level
  const filterProps = (routes: Array<any>, routesArr: Array<any>, parentPath: string = '', level: number = 0) => {
    routes.forEach((item: any) => {
      const { path, name, iocn, children } = item;

      const childrenArr: Array<any> = [];
      const actPath = parentPath ? `${parentPath}/${path}` : path;
      const actLevel: number = level + 1;

      routesArr.push({
        name, iocn,
        level: actLevel,
        path,
        actPath,
        children: childrenArr,
      });
      if(children) {
        filterProps(children, childrenArr, actPath, actLevel)
      }
    });
  }
  filterProps(configRoutes, _configMenus);

  // 根据level获取实际配置
  const sortLevel = (menus: Array<any>, menusArr: Array<any>, level: number = 1) => {
    menus.forEach((item: any) => {
      const { level: inLevel, children } = item;

      if(inLevel <= level) {
        const childrenArr: Array<any> = [];
        menusArr.push({ ...item, children: childrenArr });
        if(children) {
          sortLevel(children, childrenArr, level);
        }
      }
    });
  }
  sortLevel(_configMenus, configMenus, level);

  if(!level) {
    if(isDepth) {
      let _actMenusArr: Array<any> = [];

      // 根据父路径寻找子菜单
      const findDepth = (menus: Array<any>, parentPath: string) => {
        menus.some((item: any) => {
          const { actPath, level: inLevel, children } = item;       
          
          if(actPath === parentPath) {
            if(inLevel === 1) {
               _actMenusArr = [...children];
            }else{
              _actMenusArr = [...menus];
            }
            return true;
          }else if(children) {
            return findDepth(children, parentPath);
          }else {
            return true;
          }
        });
      }
      findDepth(_configMenus, pathname);
      
      return _actMenusArr;
    }else{
      return _configMenus;
    }
  }else {
    return configMenus;
  }
}

// 根据路由获取记录菜单key
const getCurrentMenuKeyArr = (pathname: string = ''): Array<string> => {
  let menuKeyArr: Array<string> = [];

  if(!pathname || pathname === '/') {
    menuKeyArr = ['/introduction'];
  }else {
    const _menuKeyArr: Array<string> = pathname.split('/').filter(Boolean);

    menuKeyArr = _menuKeyArr.reduce((pre: Array<string>, next: string, index: number, arr: Array<string>) => {
      const menuKey: string = '/' + arr.slice(0, index + 1).join('/');
      pre.push(menuKey);
      return pre;
    }, []);
  }

  return menuKeyArr;
}

// 通过 form 获取表单数据
const getFormData = async (form: any, validate: boolean = false) => {
  if (form) {    
    let result = {};
    if (!validate) {
      result = form.getFieldsValue();
    } else {
      await form.validateFields().then((values: any) => {
        result = { ...values };
      }).catch((err: any) => {        
        result = {};
      });
    }
    
    return result;
  }
  return {};
}

// 通过 ref 获取表单数据
const getRefFormData = (ref: any, validate: boolean = false) => {
  if (ref && ref.current) {
    const { form = {} } = ref.current.props || ref.current;
    return getFormData(form, validate);
  }
  return {};
}

// 生成Form的Item
const createFormItem = (type: string, name: string, edit: boolean) => {
  switch(type) {
    case 'string':
      return `<TextField name="${name}"${!edit ? ' disabled' : ''} />`;
    case 'number':
      return `<NumberField name="${name}"${!edit ? ' disabled' : ''} />`;
    case 'boolean':
      return `<Switch name="${name}"${!edit ? ' disabled' : ''} />`;
    case 'select':
      return `<Select name="${name}"${!edit ? ' disabled' : ''} />`;
    case 'dateTime':
      return `<DateTimePicker name="${name}"${!edit ? ' disabled' : ''} />`;
    default:
      return;
  }

}

// 创建DS的js内容
const createDsToJS = (basicData: any = {}, fieldsData: Array<any> = []) => {
  const {
    dsName = 'list',
    intlPrefix = 'hzero.common',
    readUrl = 'read',
    submitUrl,
    destroyUrl,
    autoQuery = false,
    paging = false, // 默认false, true生成额外表格配置|false生成表单额外配置
    selection = false,
    dsConfigObj = [],
  } = basicData;

  // 定义ds对象
  const DSName: string = `${dsName}DS`;
  const dsObj: any = { autoQuery, paging, selection };
  const queryFields: Array<any> = [];
  const fields: Array<any> = [];
  const tableConfig: Array<any> = [];
  const formConfig: Array<any> = [];
  const transport: any = {};

  // 生成拓展基础属性
  if(!isEmpty(dsConfigObj)) {
    dsConfigObj.forEach((item: any) => {
      setObjectProps(dsObj, item.field, item.value, item.type);
    })
  }

  // 生成field和queryField
  if(!isEmpty(fieldsData)) {
    fieldsData.forEach((item: any) => {
      const { label, name, type = 'string', isQueryField = false, isEdit = false, lookupCode } = item;
      if(!isUndefiend(label) && !isUndefiend(name)) {
        const obj = {
          label: `intl.get('${intlPrefix}.model.${name}').d('${label}')`,
          name,
          type,
        };

        if(lookupCode) {
          setObjectProps(obj, 'lookupCode', lookupCode);
          delete obj.type; // 默认独立直接不需要类型
        }

        if(isQueryField) {
          queryFields.push(obj);
        }
        fields.push(obj);

        // 生成额外配置
        if(paging) { // 表格
          const _obj = { name, align: 'center' };
          if(isEdit) {
            setObjectProps(_obj, 'editor', true);
          }
          if(['remark', 'remarks', 'reason'].some(item => name.toLowerCase().includes(item))) {
            setObjectProps(_obj, 'tooltip', 'overflow');
          }
          tableConfig.push(_obj);
        }else { // 表单
          const formItem = createFormItem(type, name, isEdit);
          formConfig.push(formItem);
        }
      }
    });
  }
  
  // 添加field和queryField
  setObjectProps(dsObj, 'queryFields', queryFields);
  setObjectProps(dsObj, 'fields', fields);

  // 生成transport
  if(readUrl) {
    const urlObj = {
      url: `\${prefix}/v1/\${organizationId}/${readUrl}`,
      method: 'GET',
    }
    setObjectProps(transport, 'read', urlObj);
  }
  if(submitUrl) {
    const urlObj = {
      url: `\${prefix}/v1/\${organizationId}/${submitUrl}`,
      method: 'POST',
    }
    setObjectProps(transport, 'submit', urlObj);
  }
  if(destroyUrl) {
     const urlObj = {
      url: `\${prefix}/v1/\${organizationId}/${destroyUrl}`,
      method: 'POST',
    }
    setObjectProps(transport, 'destroy', urlObj);
  }

  // 添加transport
  setObjectProps(dsObj, 'transport', transport);

  return { DSName, dsObj, tableConfig, formConfig };

}

// 校验表格数据
const validateTableData = (tableName: string = '表格' , data: Array<any>, rulesConfig: any) => {

  let validate: boolean = true;
  let errLine: string = '';
  let errMessage: string = '';

  const rulesKeyArr = Object.keys(rulesConfig) || [];
  if(isEmpty(rulesKeyArr) || isEmpty(data)) {
    return { validate, errLine, errMessage };
  }

  try {
    data.forEach((record: any) => {
      // 对需要校验的字段进行校验
      for(let recordKey in record) {
        if(rulesKeyArr.includes(recordKey)) {
          const recordValue = record[recordKey];
          const rulesArr = rulesConfig[recordKey];
          // eslint-disable-next-line no-loop-func
          rulesArr.forEach((rule: any) => {
            const { pattern, message = '' } = rule;
            if(recordValue && pattern && !pattern.test(recordValue)) {
              validate = false;
              errLine = `${tableName}中行存在字段格式错误`;
              errMessage = `序号${record.sortId}行: ${message}`;
              throw new Error(errMessage);
            }
          });
        }
      }
    });
  } catch (error) {
    console.log(error);
  }
  
  return { validate, errLine, errMessage };
}

export {
  getConfigMenuArr,
  getCurrentMenuKeyArr,
  getFormData,
  getRefFormData,
  createDsToJS,
  validateTableData,
}